﻿namespace PowerSong.SongDatabase
    {
    using System;

    /// <summary>
    /// Represents an entry to add or retrieve from the activity log.
    /// </summary>
    public struct LogEntry
        {

        /// <summary>
        /// Gets or sets the type of item acted upon.
        /// </summary>
        /// <value>The type of item acted upon.</value>
        public ActivityItemType Type;

        /// <summary>
        /// Gets or sets the item's ID.
        /// </summary>
        /// <value>The item's ID.</value>
        public Guid ItemID;

        /// <summary>
        /// Gets or sets the action performed.
        /// </summary>
        /// <value>The action performed.</value>
        public ActivityAction ActionPerformed;

        /// <summary>
        /// Gets or sets the time of the action.
        /// </summary>
        /// <value>The time of the action.</value>
        public DateTime Time;

        internal LogEntry(ActivityItemType type, Guid itemID, ActivityAction actionPerformed, DateTime time)
            {
            this.Type = type;
            this.ItemID = itemID;
            this.Time = time;
            this.ActionPerformed = actionPerformed;
            }

        internal static LogEntry Create(byte[] rawData)
            {

            // Get the record data
            var result = new LogEntry();
            result.Type = (ActivityItemType)rawData[0];
            result.ActionPerformed = (ActivityAction)rawData[1];
            result.Time = DateTime.FromBinary(BitConverter.ToInt64(rawData, 2));
            
            // Get the ID
            var idBytes = new Byte[16];
            Array.Copy(rawData, 10, idBytes, 0, 16);
            result.ItemID = new Guid(idBytes);
            
            // Return the result
            return result;

            }

        public byte[] ToByteArray()
            {
            var result = new byte[26];
            result[0] = (byte)Type;
            result[1] = (byte)ActionPerformed;
            Array.Copy(BitConverter.GetBytes(Time.ToBinary()), 0, result, 2, 8);
            Array.Copy(ItemID.ToByteArray(), 0, result, 10, 16);
            return result;
            }

        }

    }
